﻿@model ProductListModel

@using SDF.Core.Domain.Catalog

@{
    var defaultGridPageSize = EngineContext.Current.Resolve<SDF.Core.Domain.Common.AdminAreaSettings>().DefaultGridPageSize;
    var gridPageSizes = EngineContext.Current.Resolve<SDF.Core.Domain.Common.AdminAreaSettings>().GridPageSizes;

    //page title
    ViewBag.Title = T("Admin.Catalog.Products").Text;
    //active menu item (system name)
    Html.SetActiveMenuItemSystemName("Products");
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="content-header clearfix">
        <h1 class="pull-left">
            @T("Admin.Catalog.Products")
        </h1>
        <div class="pull-right">
            <a href="@Url.Action("Create")" class="btn bg-blue">
                <i class="fa fa-plus-square"></i>
                @T("Admin.Common.AddNew")
            </a>
            <button type="submit" name="download-catalog-pdf" class="btn bg-purple">
                <i class="fa fa-file-pdf-o"></i>
                @T("Admin.Catalog.Products.List.DownloadPDF")
            </button>
            <div class="btn-group">
                <button type="button" class="btn btn-success">
                    <i class="fa fa-download"></i>
                    @T("Admin.Common.Export")
                </button>
                <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <span class="caret"></span>
                    <span class="sr-only">&nbsp;</span>
                </button>
                <ul class="dropdown-menu" role="menu">
                    <li>
                        <button type="submit" name="exportxml-all">
                            <i class="fa fa-file-code-o"></i>
                            @T("Admin.Common.ExportToXml.All")
                        </button>
                    </li>
                    <li>
                        <button type="button" id="exportxml-selected">
                            <i class="fa fa-file-code-o"></i>
                            @T("Admin.Common.ExportToXml.Selected")
                        </button>
                    </li>
                    <li class="divider"></li>
                    <li>
                        <button type="submit" name="exportexcel-all">
                            <i class="fa fa-file-excel-o"></i>
                            @T("Admin.Common.ExportToExcel.All")
                        </button>
                    </li>
                    <li>
                        <button type="button" id="exportexcel-selected">
                            <i class="fa fa-file-excel-o"></i>
                            @T("Admin.Common.ExportToExcel.Selected")
                        </button>
                    </li>
                </ul>
            </div>
            @if (!Model.IsLoggedInAsVendor)
            {
                //a vendor cannot import products
                <button type="button" name="importexcel" class="btn bg-olive" data-toggle="modal" data-target="#importexcel-window">
                    <i class="fa fa-upload"></i>
                    @T("Admin.Common.Import")
                </button>
            }
            <button type="button" id="delete-selected" class="btn bg-red">
                <i class="fa fa-trash-o"></i>
                @T("Admin.Common.Delete.Selected")
            </button>
        </div>
    </div>

    <div class="content">
        <div class="form-horizontal">
            <div class="panel-group">
                <div class="panel panel-default panel-search">
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-5">
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.SearchProductName)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFEditorFor(model => model.SearchProductName)
                                    </div>
                                </div>
                                <div class="form-group" @(Model.AvailableCategories.SelectionIsNotPossible() ? Html.Raw("style=\"display:none\"") : null)>
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.SearchCategoryId)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFDropDownList("SearchCategoryId", Model.AvailableCategories)
                                    </div>
                                </div>
                                <div class="form-group" @(Model.AvailableCategories.SelectionIsNotPossible() ? Html.Raw("style=\"display:none\"") : null)>
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.SearchIncludeSubCategories)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFEditorFor(model => model.SearchIncludeSubCategories)
                                    </div>
                                </div>
                                <div class="form-group" @(Model.AvailableManufacturers.SelectionIsNotPossible() ? Html.Raw("style=\"display:none\"") : null)>
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.SearchManufacturerId)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFDropDownList("SearchManufacturerId", Model.AvailableManufacturers)
                                    </div>
                                </div>
                                <div class="form-group" @(Model.AvailableVendors.SelectionIsNotPossible() || Model.IsLoggedInAsVendor ? Html.Raw("style='display: none;'") : null)>
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.SearchVendorId)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFDropDownList("SearchVendorId", Model.AvailableVendors)
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-7">
                                <div class="form-group" @(Model.AvailableProjects.SelectionIsNotPossible() ? Html.Raw("style=\"display:none\"") : null)>
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.SearchProjectId)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFDropDownList("SearchProjectId", Model.AvailableProjects)
                                    </div>
                                </div>
                                <div class="form-group" @(Model.AvailableWarehouses.SelectionIsNotPossible() ? Html.Raw("style=\"display:none\"") : null)>
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.SearchWarehouseId)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFDropDownList("SearchWarehouseId", Model.AvailableWarehouses)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.SearchProductTypeId)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFDropDownList("SearchProductTypeId", Model.AvailableProductTypes)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.SearchPublishedId)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFDropDownList("SearchPublishedId", Model.AvailablePublishedOptions)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.GoDirectlyToSku)
                                    </div>
                                    <div class="col-md-8">
                                        <div class="input-group input-group-short">
                                            @Html.SDFEditorFor(model => model.GoDirectlyToSku)
                                            <span class="input-group-btn">
                                                <button type="submit" id="go-to-product-by-sku" name="go-to-product-by-sku" class="btn btn-info btn-flat">
                                                    @T("Admin.Common.Go")
                                                </button>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-7 col-md-offset-5">
                                <button type="button" id="search-products" class="btn btn-primary btn-search">
                                    <i class="fa fa-search"></i>
                                    @T("Admin.Common.Search")
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="panel panel-default">
                    <div class="panel-body">
                        <div id="products-grid"></div>

                        <script>
                            $(document).ready(function() {
                                $("#products-grid").kendoGrid({
                                    dataSource: {
                                        type: "json",
                                        transport: {
                                            read: {
                                                url: "@Html.Raw(Url.Action("ProductList", "Product"))",
                                                type: "POST",
                                                dataType: "json",
                                                data: additionalData
                                            }
                                        },
                                        schema: {
                                            data: "Data",
                                            total: "Total",
                                            errors: "Errors"
                                        },
                                        error: function(e) {
                                            display_kendoui_grid_error(e);
                                            // Cancel the changes
                                            this.cancelChanges();
                                        },
                                        pageSize: @(defaultGridPageSize),
                                        serverPaging: true,
                                        serverFiltering: true,
                                        serverSorting: true
                                    },
                                    pageable: {
                                        refresh: true,
                                        pageSizes: [@(gridPageSizes)]
                                    },
                                    editable: {
                                        confirmation: "@T("Admin.Common.DeleteConfirmation")",
                                        mode: "inline"
                                    },
                                    scrollable: false,
                                    dataBound: onDataBound,
                                    columns: [
                                        {
                                            field: "Id",
                                            headerTemplate: "<input id='mastercheckbox' type='checkbox'/>",
                                            headerAttributes: { style: "text-align:center" },
                                            attributes: { style: "text-align:center" },
                                            template: "<input type='checkbox' value='#=Id#' class='checkboxGroups'/>",
                                            width: 50
                                        },
                                        {
                                            field: "PictureThumbnailUrl",
                                            title: "@T("Admin.Catalog.Products.Fields.PictureThumbnailUrl")",
                                            template: '<img src="#=PictureThumbnailUrl#" />',
                                            width: 100
                                        },
                                        {
                                            field: "Name",
                                            title: "@T("Admin.Catalog.Products.Fields.Name")",
                                            width: 300
                                        }, {
                                            field: "Sku",
                                            title: "@T("Admin.Catalog.Products.Fields.Sku")",
                                            width: 100
                                        }, {
                                            field: "Price",
                                            title: "@T("Admin.Catalog.Products.Fields.Price")",
                                            width: 150,
                                            //if not a grouped product, then display
                                            template: "# if(ProductTypeId != @((int) ProductType.GroupedProduct)) {# #:Price# #}  #"
                                        }, {
                                            field: "StockQuantityStr",
                                            title: "@T("Admin.Catalog.Products.Fields.StockQuantity")",
                                            width: 100
                                        }, {
                                            field: "ProductTypeName",
                                            title: "@T("Admin.Catalog.Products.Fields.ProductType")",
                                            width: 100
                                        }, {
                                            field: "Published",
                                            title: "@T("Admin.Catalog.Products.Fields.Published")",
                                            width: 100,
                                            template: '# if(Published) {# <i class="fa fa-check true-icon"></i> #} else {# <i class="fa fa-close false-icon"></i> #} #'
                                        }, {
                                            field: "Id",
                                            title: "@T("Admin.Common.Edit")",
                                            width: 100,
                                            template: '<a href="Edit/#=Id#">@T("Admin.Common.Edit")</a>'
                                        }
                                    ]
                                });
                            });
                        </script>
                    </div>
                </div>
            </div>
        </div>
    </div>

            <script type="text/javascript">
                var selectedIds = [];

                $(document).ready(function () {
                    //search button
                    $('#search-products').click(function () {
                        //search
                        var grid = $('#products-grid').data('kendoGrid');
                        grid.dataSource.page(1); //new search. Set page size to 1
                        //grid.dataSource.read(); we already loaded the grid above using "page" function
                        //clear selected checkboxes
                        $('.checkboxGroups').attr('checked', false).change();
                        selectedIds = [];
                        return false;
                    });

                    $("#@Html.FieldIdFor(model => model.SearchProductName)").keydown(function (event) {
                        if (event.keyCode === 13) {
                            $("#search-products").click();
                            return false;
                        }
                    });

                    $("#@Html.FieldIdFor(model => model.GoDirectlyToSku)").keydown(function (event) {
                        if (event.keyCode === 13) {
                            $("#go-to-product-by-sku").click();
                            return false;
                        }
                    });
                    //delete selected
                    $('#delete-selected').click(function(e) {
                        e.preventDefault();

                        var postData = {
                            selectedIds: selectedIds
                        };
                        addAntiForgeryToken(postData);

                        $.ajax({
                            cache: false,
                            type: "POST",
                            url: "@(Url.Action("DeleteSelected", "Product"))",
                            data: postData,
                            complete: function(data) {
                                //reload grid
                                var grid = $('#products-grid').data('kendoGrid');
                                grid.dataSource.read();
                            },
                            error: function(xhr, ajaxOptions, thrownError) {
                                alert(thrownError);
                            },
                            traditional: true
                        });
                        return false;
                    });

                    $('#mastercheckbox').click(function () {
                        $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
                    });

                    //wire up checkboxes.
                    $('#products-grid').on('change', 'input[type=checkbox][id!=mastercheckbox]', function (e) {
                        var $check = $(this);
                        if ($check.is(":checked") == true) {
                            var checked = jQuery.inArray($check.val(), selectedIds);
                            if (checked == -1) {
                                //add id to selectedIds.
                                selectedIds.push($check.val());
                            }
                        }
                        else {
                            var checked = jQuery.inArray($check.val(), selectedIds);
                            if (checked > -1) {
                                //remove id from selectedIds.
                                selectedIds = $.grep(selectedIds, function (item, index) {
                                    return item != $check.val();
                                });
                            }
                        }
                        updateMasterCheckbox();
                    });
                });

                function additionalData() {
                    var data = {
                        SearchProductName: $('#@Html.FieldIdFor(model => model.SearchProductName)').val(),
                        SearchCategoryId: $('#SearchCategoryId').val(),
                        SearchIncludeSubCategories: $('#@Html.FieldIdFor(model => model.SearchIncludeSubCategories)').is(':checked'),
                        SearchManufacturerId: $('#SearchManufacturerId').val(),
                        SearchProjectId: $('#SearchProjectId').val(),
                        SearchWarehouseId: $('#SearchWarehouseId').val(),
                        SearchVendorId: $('#SearchVendorId').val(),
                        SearchProductTypeId: $('#SearchProductTypeId').val(),
                        SearchPublishedId: $('#SearchPublishedId').val()
                    };
                    addAntiForgeryToken(data);
                    return data;
                }

                function onDataBound(e) {
                    $('#products-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
                        var currentId = $(this).val();
                        var checked = jQuery.inArray(currentId, selectedIds);
                        //set checked based on if current checkbox's value is in selectedIds.
                        $(this).attr('checked', checked > -1);
                    });

                    updateMasterCheckbox();
                }

                function updateMasterCheckbox() {
                    var numChkBoxes = $('#products-grid input[type=checkbox][id!=mastercheckbox]').length;
                    var numChkBoxesChecked = $('#products-grid input[type=checkbox][id!=mastercheckbox]:checked').length;
                    $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
                }
            </script>
}

@*import products form*@
<div id="importexcel-window" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="importexcel-window-title">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="importexcel-window-title">@T("Admin.Common.ImportFromExcel")</h4>
            </div>
            @using (Html.BeginForm("ImportExcel", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                <div class="form-horizontal">
                    <div class="modal-body">
                        @Html.AntiForgeryToken()
                        <ul class="common-list">
                            <li>
                                <em>@T("Admin.Catalog.Products.List.ImportFromExcelTip")</em>
                            </li>
                            <li>
                                <em>@T("Admin.Common.ImportFromExcel.ManyRecordsWarning")</em>
                            </li>
                        </ul>
                        <div class="form-group">
                            <div class="col-md-2">
                                <div class="label-wrapper">
                                    <label class="control-label">
                                        @T("Admin.Common.ExcelFile")
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-10">
                                <input type="file" id="importexcelfile" name="importexcelfile" class="form-control" />
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">
                            @T("Admin.Common.ImportFromExcel")
                        </button>
                    </div>
                </div>
            }
        </div>
    </div>
</div>

@*export selected (XML). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
@using (Html.BeginForm("ExportXmlSelected", "Product", FormMethod.Post, new { id = "export-xml-selected-form" }))
{
    @Html.AntiForgeryToken()
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
}

<script type="text/javascript">
    $(document).ready(function () {
        $('#exportxml-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#export-xml-selected-form #selectedIds').val(ids);
            $('#export-xml-selected-form').submit();
            return false;
        });
    });
</script>

@*export selected (Excel). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
@using (Html.BeginForm("ExportExcelSelected", "Product", FormMethod.Post, new { id = "export-excel-selected-form" }))
{
    @Html.AntiForgeryToken()
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
}

<script type="text/javascript">
    $(document).ready(function () {
        $('#exportexcel-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#export-excel-selected-form #selectedIds').val(ids);
            $('#export-excel-selected-form').submit();
            return false;
        });
    });
</script>
